<script setup lang="ts">
import UploadPicture from '@/components/UploadPicture.vue'
import { computed, h, onMounted, reactive, ref } from 'vue'
import {
  listPictureTagCategoryUsingGet,
  userGetPicByIdUsingGet,
  userUpdatePicUsingPost,
} from '@/api/fileController.ts'
import { message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import UrlUploadPicture from '@/components/UrlUploadPicture.vue'
import { EditOutlined } from '@ant-design/icons-vue'
import PicCropper from '@/components/PicCropper.vue'
import PicAIHandle from '@/components/PicAIHandle.vue'
import { getSpaceByIdUsingGet, getSpaceTypeByPictureIdUsingGet } from '@/api/spaceController.ts'

const router = useRouter()
const route = useRoute()

//定义属性接收子组件的传值
const picture = ref<API.PictureVO>()
//父组件在 onSuccess 方法中接收子组件传回的数据，并更新自身的 picture 状态
const onSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
  pictureForm.name = newPicture.name
}

const pictureForm = reactive<API.Picture>({})

//存储分类
const categoryOptions = ref<string[]>([])
//存储标签
const tagOptions = ref<string[]>([])

//tab默认选中
const urlOrCommon = ref('common')

//接收空间ID
const spaceId = computed(() => {
  return route.query.spaceId
})

//空间类型
const spaceType = ref()
/**
 * 编辑图片子组件的引用
 */
const picCropperRef = ref()

/**
 * AI扩图的引用
 */
const picAIHandleRef = ref()

/**
 * 页面加载完成后调用
 */
onMounted(() => {
  listPictureTagCategory()
  getPictureById()
  getSpaceById()
})

/**
 * 调用后端获取图片标签的接口
 */
async function listPictureTagCategory() {
  const resp = await listPictureTagCategoryUsingGet()
  if (resp.data.data && resp.data.code === 0) {
    categoryOptions.value = (resp.data.data.categoryList ?? []).map((data: string) => {
      return {
        value: data,
        label: data,
      }
    })
    tagOptions.value = (resp.data.data.tagList ?? []).map((data: string) => {
      return {
        value: data,
        label: data,
      }
    })
  } else {
    console.log('调用后端获取图片标签的接口失败', resp.data.message)
  }
}

/**
 * 提交编辑图片请求
 * @param any
 */
async function submit(values: any) {
  const pictureId = picture.value.id
  if (!pictureId) {
    return
  }
  const resp = await userUpdatePicUsingPost({
    id: pictureId,
    ...values,
  })
  if (resp.data.code === 0 && resp.data.data) {
    message.success('创建成功')
    //跳转到详情页
    router.push(`/picture/detail/${pictureId}`)
  } else {
    message.error('创建失败' + resp.data.message)
  }
}

/**
 * 根据id查询图片信息
 */
async function getPictureById() {
  const id = route.query?.id
  if (id) {
    const resp = await userGetPicByIdUsingGet({ id: id })
    if (resp.data.code === 0 && resp.data.data) {
      const data = resp.data.data
      picture.value = data
      pictureForm.name = data.name
      pictureForm.introduction = data.introduction
      pictureForm.tags = data.tags
      pictureForm.category = data.category
    } else {
      console.log('根据id查询图片信息错误')
    }
  }
}

/**
 * 根据空间ID查询后端接口
 */
const getSpaceById = async () => {
  const id = route.query.spaceId
  if (id) {
    const resp = await getSpaceByIdUsingGet({
      id: id,
    })
    if (resp.data.code === 0 && resp.data.data) {
      spaceType.value = resp.data.data.spaceType
    } else {
      console.log('根据空间ID查询后端接口失败', resp.data.message)
    }
  }else {
    const pictureId = route.query?.id
    //利用图片ID查询出该图片对应的空间情况
    const resp = await getSpaceTypeByPictureIdUsingGet({
      pictureId:pictureId,
    })
    if (resp.data.code === 0 && resp.data.data) {
      spaceType.value = resp.data.data
    }else {
      console.log('根据图片ID查询后端接口失败', resp.data.message)
    }
  }

}

//控制AI扩图前置确定框是否展示
const AIHandlerCfmModalOpen = ref<boolean>(false)
/**
 * 展示AI扩图前置确定框
 */
const showAIHandlerCfmModal = () => {
  AIHandlerCfmModalOpen.value = true
}

/**
 * 点击AI扩图前置确定框的确认按钮时
 * @param e
 */
const handleOk = (e: MouseEvent) => {
  //AI扩图 打开子组件
  if (picAIHandleRef.value) {
    picAIHandleRef.value.handleOpen()
    AIHandlerCfmModalOpen.value = false
  }
}

/**
 * 子组件上传成功的回调，刷新父组件的picture为最新的值
 * @param newPicture
 */
function onCropperSuccess(newPicture: API.PictureVO) {
  picture.value = newPicture
}

function onAISuccess(newPicture: API.PictureVO) {
  picture.value = newPicture
}

/**
 * 图片编辑 打开子组件
 */
function doPicCropper() {
  if (picCropperRef.value) {
    picCropperRef.value.handleOpen()
  }
}

</script>

<template>
  <div id="addPicture">
    <!--    UploadPicture是本组件的子组件-->
    <!--    UploadPicture组件，在页面上的体现是上传图片框-->
    <h2 class="title">{{ route.query?.id ? '云图库-图片修改' : '云图库-图片新增' }}</h2>
    <a-typography-paragraph type="secondary" v-if="spaceId != null">
      保存至空间 <a :href="`/space/detail/${spaceId}`">{{ spaceId }}</a>
    </a-typography-paragraph>

    <a-tabs v-model:activeKey="urlOrCommon">
      <a-tab-pane key="common" tab="文件上传">
        <!--    父组件通过 :picture="picture" 将 picture 变量传递给子组件UploadPicture
父组件通过 :onSuccess="onSuccess" 传递一个回调函数给子组件UploadPicture-->
        <UploadPicture :picture="picture" :onSuccess="onSuccess" :spaceId="spaceId" />
      </a-tab-pane>
      <a-tab-pane key="url" tab="链接上传" force-render>
        <UrlUploadPicture :picture="picture" :onSuccess="onSuccess" :spaceId="spaceId" />
      </a-tab-pane>
    </a-tabs>

    <!--    以下是图片上传的表单-->
    <a-form
      :model="pictureForm"
      name="RegisterForm"
      autocomplete="off"
      layout="vertical"
      @finish="submit"
      v-if="picture"
    >
      <div style="display: flex; justify-content: center">
        <a-space>
          <div>
            <a-button :icon="h(EditOutlined)" @click="doPicCropper">图片编辑</a-button>
            <!--        编辑图片子组件-->
            <PicCropper
              :on-success="onCropperSuccess"
              :picture="picture"
              :spaceId="picture.spaceId"
              :image-url="picture?.url"
              :space-type="spaceType"
              ref="picCropperRef"
            ></PicCropper>
          </div>
          <div>
            <a-button :icon="h(EditOutlined)" @click="showAIHandlerCfmModal">AI扩图</a-button>
            <a-modal v-model:open="AIHandlerCfmModalOpen" title="AI扩图提示" @ok="handleOk">
              <a-typography-paragraph>
                <p>图像限制：</p>
                <p>图像格式：JPG、JPEG、PNG、HEIF、WEBP。</p>
                <p>图像分辨率：不低于512×512像素且不超过4096×4096像素。</p>
                <p>图像单边长度范围：[512, 4096]，单位像素。</p>
              </a-typography-paragraph>
            </a-modal>
            <PicAIHandle
              :on-success="onAISuccess"
              :picture="picture"
              :spaceId="picture.spaceId"
              ref="picAIHandleRef"
            >
            </PicAIHandle>
          </div>
        </a-space>
      </div>

      <!--      名称,一定要指定name属性-->
      <a-form-item name="name" label="名称">
        <a-input v-model:value="pictureForm.name" placeholder="请输入名称" />
      </a-form-item>
      <!--      简介，用文本域-->
      <a-form-item name="introduction" label="简介">
        <a-textarea
          v-model:value="pictureForm.introduction"
          placeholder="请输入简介"
          :auto-size="{ minRows: 2, maxRows: 5 }"
          allowClear
        />
      </a-form-item>
      <!--      分类，用自动完成-->
      <a-form-item name="category" label="分类">
        <a-auto-complete
          v-model:value="pictureForm.category"
          :options="categoryOptions"
          placeholder="请选择分类"
          allowClear
        />
      </a-form-item>

      <!--      标签，用选择框-->
      <a-form-item name="tags" label="标签">
        <a-select
          v-model:value="pictureForm.tags"
          mode="tags"
          style="width: 100%"
          placeholder="请选择标签"
          :options="tagOptions"
          allowClear
        ></a-select>
      </a-form-item>

      <a-form-item>
        <a-button type="primary" html-type="submit" style="width: 100%">创建</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<style scoped>
#addPicture {
  max-width: 720px;
  margin: 0 auto;
}
</style>
